package com.lian.chatroom.server.session;


import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionMemoryImpl implements Session{

    //存储用户名和对应绑定通道，根据用户名查询通道
    private final Map<String, Channel> usernameChannelMap = new ConcurrentHashMap<>();
    //为了查询方便，根据通道查询用户名
    private final Map<Channel,String> channelUsernameMap = new ConcurrentHashMap<>();
    //通道的属性集合
    private final Map<Channel,Map<String,Object>> channelAttributesmap = new ConcurrentHashMap<>();

    @Override
    public void bind(Channel channel,String username) {
        usernameChannelMap.put(username,channel);
        channelUsernameMap.put(channel,username);
        channelAttributesmap.put(channel,new ConcurrentHashMap<>());
    }

    @Override
    public void unbind(Channel channel) {
        //根据通道获取对应绑定的用户
        String username = channelUsernameMap.get(channel);
        //再从集合中删除掉指定的用户
        usernameChannelMap.remove(username);
        //再从集合中删除掉指定用户对应绑定的通道
        channelAttributesmap.remove(channel);
    }

    @Override
    public Object getAttribute(Channel channel, String name) {
        return channelAttributesmap.get(channel).get(name);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        channelAttributesmap.get(channel).put(name,value);
    }

    @Override
    public Channel getChannel(String username) {
        return usernameChannelMap.get(username);
    }
}
